package loengud.w04;

/**
 * An example about exceptions.
 * @author Ago
 *
 */
public class ExceptionExample {

	/**
	 * Infamous main.
	 * @param args Arguments
	 */

	public static void main(String[] args) {
		// Math.sqrt just returns NaN
		System.out.println(Math.sqrt(-1));
		try {
			System.out.println(sqrt(-1));
		} catch (NumberFormatException e) {
			/*
			 * As NumberFormatException is 
			 * a subclass of IllegalArgumentException
			 * we have to catch NumberFormatException first.
			 * 
			 * Otherwise IllegalArgumentException would
			 * catch both IllegalArumentException and
			 * NumberFormatException.
			 * 
			 * And as all the exceptions are subclasses
			 * of Exception, then catching Exception is 
			 * the last block.
			 * 
			 * try {
			 * 
			 * } catch (Exception e) {
			 * 
			 * }
			 * 
			 * will catch all the exceptions which might 
			 * occur during the execution of try block.
			 */
			System.out.println("argument was wrong." + e.getMessage());			
		} catch (IllegalArgumentException e) {
			/*
			 * If the exception occurred in the try block 
			 * wasn't of type NumberFormatException, 
			 * we can end up here.
			 */
			System.out.println("argument was wrong." + e.getMessage());
		} catch (Exception e) {
			/*
			 * All the other exceptions are caught here.
			 * 
			 * If the exception occurred in the try block 
			 * wasn't of the type NumberFormatException nor
			 * IllegalArgumentException,
			 * we will end up here.
			 * 
			 */
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * Calculates the square root of the argument.
	 * 
	 * Notice how it throws different type of exceptions.
	 * Those don't make sense, but we use those
	 * to illustrate how different type of exceptions
	 * are handled.
	 * 
	 * Also, note that NumberFormatException is the subclass
	 * of IllegalArgumentException.
	 * 
	 * @param a Argument to be used
	 * @return Square-root of a
	 * @throws IllegalArgumentException In case the argument is negative
	 * @throws NumberFormatException In case the argument is "too large"
	 */
	public static double sqrt(int a) 
			throws IllegalArgumentException, NumberFormatException {
		if (a < 0) {
			//throw new NegativeNumberException();
			throw new IllegalArgumentException("argument of sqrt cannot be negative");
			
		}
		if (a > 100) {
			//throw new TooLargeNumberException();
			throw new NumberFormatException("too large");
		}
		return Math.sqrt(a);
	}

}
